package org.jeecg.modules.flowable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.flowable.common.util.IdUtil;
import org.jeecg.modules.flowable.common.util.json.ObjectConvert;
import org.jeecg.modules.flowable.common.util.validation.AssertValid;
import org.jeecg.modules.flowable.common.util.validation.MustParamValidation;
import org.jeecg.modules.flowable.dic.DictKey;
import org.jeecg.modules.flowable.entity.TActFengFormEntity;
import org.jeecg.modules.flowable.exception.ModuleFlowableException;
import org.jeecg.modules.flowable.mapper.ExtFlowableMapper;
import org.jeecg.modules.flowable.mapper.TActFengFormMapper;
import org.jeecg.modules.flowable.service.FormService;
import org.jeecg.modules.flowable.service.ITActFengFormService;
import org.jeecg.modules.flowable.service.bo.FengForm;
import org.jeecg.modules.flowable.system.core.SystemUser;
import org.jeecg.modules.flowable.system.etc.SystemUserUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Title:  <br>
 * Desc:  <br>
 * Date: 6/15/22 10:57 AM <br>
 * Company: 联通（辽宁）产业互联网有限公司 <br>
 *
 * @author zxd
 * @version 1.0.0
 */
@Service
public class FormServiceImpl implements FormService {

    @Autowired
    private TActFengFormMapper tActFengFormMapper;
    @Autowired
    private ITActFengFormService iTActFengFormService;
    @Autowired
    private ExtFlowableMapper extFlowableMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Page<FengForm> queryFormList(String argFormName, String argFormKey, String argFormType, Integer argCurrPage, Integer argPageSize) {

        MustParamValidation.mustValidation(argCurrPage,argPageSize);
        Page<TActFengFormEntity> tActFengFormEntityPage = extFlowableMapper.queryLastFengForm(new Page<>(argCurrPage, argPageSize),argFormName,argFormKey,argFormType,null);
        // 查询字典项
        Map<String, String> dictMap = queryFormTypeDict();
        // 匹配字典项
        List<TActFengFormEntity> records = tActFengFormEntityPage.getRecords();
        List<FengForm> list2 = new ArrayList<>();;
        for (TActFengFormEntity record : records) {
            FengForm f= ObjectConvert.convert(record, FengForm.class);
            f.setCategoryName(dictMap.get(f.getCategoryId()));
            list2.add(f);
        }
        Page<FengForm> fengFormPage = new Page<>(tActFengFormEntityPage.getCurrent(), tActFengFormEntityPage.getSize(), tActFengFormEntityPage.getTotal());
        fengFormPage.setRecords(list2);
        return fengFormPage;
    }

    @Override
    public Page<FengForm> queryEffectiveFormList(String argFormName, String argFormKey, String argFormType, Integer argCurrPage, Integer argPageSize) {
        MustParamValidation.mustValidation(argCurrPage,argPageSize);
        Page<TActFengFormEntity> tActFengFormEntityPage = extFlowableMapper.queryLastFengForm(new Page<>(argCurrPage, argPageSize),argFormName,argFormKey,argFormType,1);
        // 查询字典项
        Map<String, String> dictMap = queryFormTypeDict();
        // 匹配字典项
        List<TActFengFormEntity> records = tActFengFormEntityPage.getRecords();
        List<FengForm> list2 = new ArrayList<>();;
        for (TActFengFormEntity record : records) {
            FengForm f= ObjectConvert.convert(record, FengForm.class);
            f.setCategoryName(dictMap.get(f.getCategoryId()));
            list2.add(f);
        }
        Page<FengForm> fengFormPage = new Page<>(tActFengFormEntityPage.getCurrent(), tActFengFormEntityPage.getSize(), tActFengFormEntityPage.getTotal());
        fengFormPage.setRecords(list2);
        return fengFormPage;
    }

    @Override
    public Page<FengForm> queryFormListByKey(String argKey,Integer argCurrPage, Integer argPageSize) {

        MustParamValidation.mustValidation(argKey);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getFormKey, argKey);
        queryWrapper.eq(TActFengFormEntity::getDelFlag,0);
        queryWrapper.orderByDesc(TActFengFormEntity::getFormVersion);
        Page<TActFengFormEntity> page = tActFengFormMapper.selectPage(new Page<TActFengFormEntity>(argCurrPage, argPageSize), queryWrapper);
        // 查询字典项
        Map<String, String> dictMap = queryFormTypeDict();

        List<FengForm> list2 = new ArrayList<>();;
        for (TActFengFormEntity record : page.getRecords()) {
            FengForm f= ObjectConvert.convert(record, FengForm.class);
            f.setCategoryName(dictMap.get(f.getCategoryId()));
            list2.add(f);
        }
        Page<FengForm> fengFormPage = new Page<>();
        fengFormPage.setRecords(list2);
        fengFormPage.setCountId(page.getCountId());
        fengFormPage.setCurrent(page.getCurrent());
        fengFormPage.setMaxLimit(page.getMaxLimit());
        fengFormPage.setSize(page.getSize());
        fengFormPage.setTotal(page.getTotal());
        fengFormPage.setPages(page.getPages());
        return fengFormPage;
    }

    @Override
    public String queryFormDesigner(String argFormId) {
        TActFengFormEntity tActFengFormEntity = tActFengFormMapper.selectById(argFormId);
        if(AssertValid.isEmpty(tActFengFormEntity))
            return null;
        else
            return tActFengFormEntity.getFormContent();
    }

    @Override
    public FengForm queryFormByKey(String argKey) {
        MustParamValidation.mustValidation(argKey);
        Integer version = 0;
        List<Map<String, Object>> maps = extFlowableMapper.queryFormLastVersionByKey(argKey);
        if(AssertValid.isNotEmpty(maps) && maps.get(0)!=null) {
            version = Integer.valueOf(maps.get(0).get("MAX_VERSION").toString());
        }
        // 查询最新的表单
        MustParamValidation.mustValidation(argKey);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getFormKey, argKey);
        queryWrapper.eq(TActFengFormEntity::getDelFlag,0);
        queryWrapper.eq(TActFengFormEntity::getFormVersion,version);
        List<TActFengFormEntity> tActFengFormEntities = tActFengFormMapper.selectList(queryWrapper);
        if(AssertValid.isNotEmpty(tActFengFormEntities)) {
            TActFengFormEntity tActFengFormEntity = tActFengFormEntities.get(0);
            // 去字典里面查询分类名称
            FengForm convert = ObjectConvert.convert(tActFengFormEntity, FengForm.class);
            Map<String, String> dictMap = queryFormTypeDict();
            convert.setCategoryName(dictMap.get(convert.getCategoryId()));
            return convert;
        }
        return null;
    }

    @Override
    public FengForm queryActiveFormByKey(String argKey) {
        MustParamValidation.mustValidation(argKey);
        Integer version = 0;
        List<Map<String, Object>> maps = extFlowableMapper.queryFormLastVersionByKey(argKey);
        if(AssertValid.isNotEmpty(maps) && maps.get(0)!=null) {
            version = Integer.valueOf(maps.get(0).get("MAX_VERSION").toString());
        }
        // 查询最新的表单
        MustParamValidation.mustValidation(argKey);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getFormKey, argKey);
        queryWrapper.eq(TActFengFormEntity::getDelFlag,0);
        queryWrapper.eq(TActFengFormEntity::getFormStatus,1);
        queryWrapper.eq(TActFengFormEntity::getFormVersion,version);
        List<TActFengFormEntity> tActFengFormEntities = tActFengFormMapper.selectList(queryWrapper);
        if(AssertValid.isNotEmpty(tActFengFormEntities)) {
            TActFengFormEntity tActFengFormEntity = tActFengFormEntities.get(0);
            // 去字典里面查询分类名称
            FengForm convert = ObjectConvert.convert(tActFengFormEntity, FengForm.class);
            Map<String, String> dictMap = queryFormTypeDict();
            convert.setCategoryName(dictMap.get(convert.getCategoryId()));
            return convert;
        }
        return null;
    }

    @Override
    public FengForm queryFormListById(String argId) {
        MustParamValidation.mustValidation(argId);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getId, argId);
        queryWrapper.eq(TActFengFormEntity::getDelFlag,0);
        List<TActFengFormEntity> tActFengFormEntities = tActFengFormMapper.selectList(queryWrapper);
        if(AssertValid.isNotEmpty(tActFengFormEntities)) {
            // 查询字典项
            Map<String, String> dictMap = queryFormTypeDict();
            FengForm f= ObjectConvert.convert(tActFengFormEntities.get(0), FengForm.class);
            f.setCategoryName(dictMap.get(f.getCategoryId()));
            return f;
        } else {
            return null;
        }
    }

    @Override
    @Transactional
    public FengForm save(TActFengFormEntity argTActFengFormEntity) {
        SystemUser loginUser = SystemUserUtil.getSystemUser();
        MustParamValidation.mustValidation(argTActFengFormEntity.getCategoryId(),argTActFengFormEntity.getFormContent(),argTActFengFormEntity.getFormName());
        DateTime now = DateTime.now();
        String id= IdUtil.getStringId();

        // 查询字典项
        Map<String, String> dictMap = queryFormTypeDict();
        String s = dictMap.get(argTActFengFormEntity.getCategoryId());
        if(AssertValid.isEmpty(s))
            throw new ModuleFlowableException("表单类型在字典项中不存在");

        if(AssertValid.isEmpty(argTActFengFormEntity.getId())) {
            // 新增
            // 判断KEY是否存在
            List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT count(*) as NUM FROM t_act_feng_form where FORM_KEY = '" + argTActFengFormEntity.getFormKey() + "' and DEL_FLAG =0");
            Integer num = Integer.valueOf(maps.get(0).get("NUM").toString());
            if(num.intValue()>0)
                throw new ModuleFlowableException("表单KEY已经存在，不能重复创建");
            argTActFengFormEntity.setId(id);
            argTActFengFormEntity.setFormStatus(1);
            argTActFengFormEntity.setUpdateTime(now.toDate());
            argTActFengFormEntity.setUpdateBy(loginUser.getRealname());
            argTActFengFormEntity.setCreateBy(loginUser.getRealname());
            argTActFengFormEntity.setCreateTime(now.toDate());
            argTActFengFormEntity.setDelFlag(0);
            argTActFengFormEntity.setFormVersion(1);
            tActFengFormMapper.insert(argTActFengFormEntity);
            FengForm ff=ObjectConvert.convert(argTActFengFormEntity, FengForm.class);
            ff.setCategoryName(s);
            return ff;
        } else {
            // 修改
            // 查询当前最高版本
            List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT MAX(FORM_VERSION) as NUM FROM t_act_feng_form where FORM_KEY = '" + argTActFengFormEntity.getFormKey() + "' and DEL_FLAG =0");
            Integer vers = 1;
            if(AssertValid.isNotEmpty(maps.get(0).get("NUM"))) {
                vers = Integer.valueOf(maps.get(0).get("NUM").toString());
                vers++ ;
            }
            // 查询原表单信息
            TActFengFormEntity tActFengFormEntity = tActFengFormMapper.selectById(argTActFengFormEntity.getId());

            argTActFengFormEntity.setId(id);
            argTActFengFormEntity.setCreateTime(tActFengFormEntity.getCreateTime());
            argTActFengFormEntity.setCreateBy(tActFengFormEntity.getCreateBy());
            argTActFengFormEntity.setFormKey(tActFengFormEntity.getFormKey());
            argTActFengFormEntity.setFormStatus(1);
            argTActFengFormEntity.setUpdateTime(now.toDate());
            argTActFengFormEntity.setUpdateBy(loginUser.getRealname());
            argTActFengFormEntity.setDelFlag(0);
            argTActFengFormEntity.setFormVersion(vers);
            tActFengFormMapper.insert(argTActFengFormEntity);
            FengForm ff=ObjectConvert.convert(argTActFengFormEntity, FengForm.class);
            ff.setCategoryName(s);
            // 更新表单名称
            LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
            queryWrapper.eq(TActFengFormEntity::getFormKey,argTActFengFormEntity.getFormKey());
            TActFengFormEntity tActFengFormEntity1 = new TActFengFormEntity().setFormName(argTActFengFormEntity.getFormName());
            tActFengFormMapper.update(tActFengFormEntity1,queryWrapper);

            return ff;
        }
    }

    @Override
    public void formSupend(String argFormId) {
        SystemUser loginUser = SystemUserUtil.getSystemUser();
        MustParamValidation.mustValidation(argFormId);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getId, argFormId);

        DateTime now = DateTime.now();
        TActFengFormEntity entity = new TActFengFormEntity().setId(argFormId).setFormStatus(0).setUpdateBy(loginUser.getRealname()).setUpdateTime(now.toDate());
        tActFengFormMapper.update(entity,queryWrapper);
    }

    @Override
    public void formActive(String argFormId) {
        SystemUser loginUser = SystemUserUtil.getSystemUser();
        MustParamValidation.mustValidation(argFormId);
        LambdaQueryWrapper<TActFengFormEntity> queryWrapper = new LambdaQueryWrapper<TActFengFormEntity>();
        queryWrapper.eq(TActFengFormEntity::getId, argFormId);

        DateTime now = DateTime.now();
        TActFengFormEntity entity = new TActFengFormEntity().setId(argFormId).setFormStatus(1).setUpdateBy(loginUser.getRealname()).setUpdateTime(now.toDate());
        tActFengFormMapper.update(entity,queryWrapper);
    }
    // 查询表单字典
    private Map<String,String> queryFormTypeDict() {
        List<Map<String, Object>> list = extFlowableMapper.queryDictItem(DictKey.FLOWABLE_FORM_TYPE);
        Map<String, String> dictMap = list.stream().collect(Collectors.toMap(item -> {
            return item.get("dictValue").toString();
        }, item -> {
            return item.get("dictLabel").toString();
        },(v1,v2)-> v1));
        return dictMap;
    }
}